package cn.tworice.ip.util;

import cn.tworice.common.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;

public class IpAddrUtils {
    public static String getIpAddr(HttpServletRequest request) {
        String Xip = request.getHeader("X-Real-IP");
        String XFor = request.getHeader("X-Forwarded-For");
        if(!StringUtils.isEmpty(XFor) && !"unknown".equalsIgnoreCase(XFor)){
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = XFor.indexOf(",");
            if(index != -1){
                return XFor.substring(0,index);
            }else{
                return XFor;
            }
        }
        XFor = Xip;
        if(!StringUtils.isEmpty(XFor) && !"unknown".equalsIgnoreCase(XFor)){
            return XFor;
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getRemoteAddr();
        }
        return XFor;
    }

    /**
     * 将IP转为数字
     * @param ip IP地址
     * @return long
     **/
    public static long IPToLong(String ip)
    {
        String[] ipBytes;
        double num = 0;
        if(!StringUtils.isEmpty(ip)){
            ipBytes = ip.split("\\.");
            for (int i = ipBytes.length - 1; i >= 0; i--){
                num += ((Integer.parseInt(ipBytes[i]) % 256) * Math.pow(256, (3 - i)));
            }
        }
        return (long)num;
    }

    /**
     * 获取IP字符串
     * @param inetAddress
     * @return java.lang.String
     * @author 二饭 [2023/3/7]
     **/
    public static String getIP(InetAddress inetAddress) {
        return inetAddress.getHostAddress();
    }

    /**
     * 获取归属地
     * @param ip IP地址
     * @return java.lang.String
     * @author 二饭 [2023/3/7]
     **/
    public static String getIP_INFO(String ip) {
        try {
            String urlStr = "http://ip.taobao.com/service/getIpInfo.php?ip=" + ip;
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);

            if (conn.getResponseCode() == 200) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                reader.close();

                // 解析响应结果
                String result = sb.toString();
                String country = result.split(":")[7].split(",")[0].replaceAll("\"", "");
                String region = result.split(":")[11].split(",")[0].replaceAll("\"", "");
                String city = result.split(":")[15].split(",")[0].replaceAll("\"", "");
                System.out.println("归属地：" + country + region + city);
            } else {
                System.out.println("查询失败，响应码为：" + conn.getResponseCode());
            }
        } catch (Exception e) {
            System.out.println("查询失败，" + e.getMessage());
        }
        return null;
    }
}
